package com.xsth.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;

/**
 * 连接服务器的数据库 主数据库
 * 
 * @author liulinsen
 *
 */
@Configuration
// 扫描 Mapping 接口并容器管理
@MapperScan(basePackages = HostDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "hostSqlSessionFactory")
public class HostDataSourceConfig {
	// 精确到 host 目录，以便跟其他数据源隔离
	static final String PACKAGE = "com.xsth.mapping.host";
	static final String MAPPER_LOCATION = "classpath:mapper/host/*.xml";

	@Value("${host.datasource.url}")
	private String url;

	@Value("${host.datasource.username}")
	private String user;

	@Value("${host.datasource.password}")
	private String password;

	@Value("${host.datasource.driverClassName}")
	private String driverClass;

	@Bean(name = "hostDataSource")
	@Primary
	public DataSource hostDataSource() {
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setDriverClassName(driverClass);
		dataSource.setUrl(url);
		dataSource.setUsername(user);
		dataSource.setPassword(password);
		return dataSource;
	}

	/**
	 * 事务管理
	 * 
	 * @return
	 */
	@Bean(name = "hostTransactionManager")
	/**
	 * @Primary 标志这个 Bean 如果在多个同类 Bean 候选时，该 Bean 优先被考虑。
	 *          「多数据源配置的时候注意，必须要有一个主数据源.
	 */
	@Primary
	public DataSourceTransactionManager hostTransactionManager() {
		return new DataSourceTransactionManager(hostDataSource());
	}

	/**
	 * 创建SqlSessionFactory工厂
	 * 
	 * @param hostDataSource
	 * @return
	 * @throws Exception
	 */
	@Bean(name = "hostSqlSessionFactory")
	@Primary
	public SqlSessionFactory hostSqlSessionFactory(@Qualifier("hostDataSource") DataSource hostDataSource)
			throws Exception {
		final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
		sessionFactory.setDataSource(hostDataSource);
		sessionFactory.setMapperLocations(
				new PathMatchingResourcePatternResolver().getResources(HostDataSourceConfig.MAPPER_LOCATION));
		return sessionFactory.getObject();
	}
}
